package com.ruoyi.web.controller;

import com.ruoyi.config.AppConfig;
import com.ruoyi.config.ServerConfig;
import com.ruoyi.utils.AliCosUtils;
import com.ruoyi.utils.FileUtil;
import com.ruoyi.utils.ResponseResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author tanxingxian
 * @date 2022-01-12 15:22
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public ResponseResult uploadFile(MultipartFile file) throws Exception {
        try {
//            // 上传文件路径
//            String filePath = AppConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUtil.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;

            String fileName = UUID.randomUUID().toString();
            String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename());
            String filePath = fileName + "" + extension;
            String url = AliCosUtils.uploadFile(file, "yytfile/upload/2022/04/22/" + filePath);

            Map<String, String> data = new HashMap<>(2);
            data.put("fileName", fileName);
            data.put("url", url);
            return ResponseResult.success(data);
        } catch (Exception e) {
            return ResponseResult.failure(e.getMessage());
        }
    }


}
